//充值提现页面内容  正确返回数据
import React, { useState, useEffect } from 'react';
import { Card, Space,Statistic,Cascader, InputNumber, Select,Button,Modal,message  } from 'antd';
import { SettingOutlined } from '@ant-design/icons';
import { Link, useRouter } from 'next/router';
import axios from 'axios';

const Money = () => {
  const router = useRouter();
  const [totalAsset, setTotalAsset] = useState(0);
  const [totalProfit, setTotalProfit] = useState(0);
  const [yesterdayProfit, setYesterdayProfit] = useState(0);
  const [totalProfitRate, setTotalProfitRate] = useState(0);
  const [stockValue, setStockValue] = useState(0);
  const [cash, setCash] = useState([]);
  const [rechargeAmount, setRechargeAmount] = useState(100); // 默认充值金额
  const [withdrawAmount, setWithdrawAmount] = useState(100); // 默认提现金额

const { Option } = Select;
const selectBefore = (
  <Select
    defaultValue="add"
    style={{
      width: 60,
    }}
  >
    <Option value="add">+</Option>
    <Option value="minus">-</Option>
  </Select>
);
const selectAfter = (
  <Select
    defaultValue="USD"
    style={{
      width: 60,
    }}
  >
    <Option value="USD">$</Option>
    <Option value="EUR">€</Option>
    <Option value="GBP">£</Option>
    <Option value="CNY">¥</Option>
  </Select>
);

// 对话框——确定充值
const [isModalOpen1, setIsModalOpen1] = useState(false);
const showModal1 = () => {
  setIsModalOpen1(true);
};
const handleOk1 = async () => {
  setIsModalOpen1(false);
  try {
    const token = localStorage.getItem('token');
    const response = await axios.post('/api/user/money_recharge', {
      add_money: rechargeAmount
    }, {
      headers: {
        Authorization: `Bearer ${token}`
      }
    });
    message.success('充值成功');
    router.push('/money');//充值成功后返回资产页面
  } catch (error) {
    if (error.response) {
      const { status, data } = error.response;
      if (status === 401) {
        message.error('登录已过期，请重新登录');
        localStorage.removeItem('token');
        router.push('/login');
      } else if (status === 400) {
        message.error(data.msg || '充值失败');
      } else {
        message.error('发生未知错误');
      }
    } else if (error.request) {
      message.error('服务器未响应');
    } else {
      message.error('请求失败');
    }
  }
};

const handleCancel1 = () => {
  setIsModalOpen1(false);
};

// 对话框——确定提现
const [isModalOpen2, setIsModalOpen2] = useState(false);
const showModal2 = () => {
  setIsModalOpen2(true);
};
const handleOk2 = async () => {
  setIsModalOpen2(false);
  try {
    const token = localStorage.getItem('token');
    const response = await axios.post('/api/user/money_withdraw', {
      reduce_money: withdrawAmount
    }, {
      headers: {
        Authorization: `Bearer ${token}`
      }
    });
    message.success('提现成功');
    router.push('/money');//提现成功后返回资产页面
  } catch (error) {
    if (error.response) {
      const { status, data } = error.response;
      if (status === 401) {
        message.error('登录已过期，请重新登录');
        localStorage.removeItem('token');
        router.push('/login');
      } else if (status === 400) {
        message.error(data.msg || '提现失败');
      } else {
        message.error('发生未知错误');
      }
    } else if (error.request) {
      message.error('服务器未响应');
    } else {
      message.error('请求失败');
    }
  }
};

const handleCancel2 = () => {
  setIsModalOpen2(false);
};

//获取用户资产信息
useEffect(() => {
  const fetchData = async () => {
    try {
      // 假设您的Token存储在localStorage中
      const token = localStorage.getItem('token');
      const response = await axios.get('/api/user/wealth_info', {
        headers: {
          Authorization: `Bearer ${token}`
        }
      });
      const data = response.data.data;
        setCash(data.cash);
        setTotalAsset(data.total_asset);
        setTotalProfit(data.total_profit);
        setYesterdayProfit(data.yesterday_profit);
        setTotalProfitRate(data.total_profit_rate);
        setStockValue(data.stock_value);
    } catch (error) {
      console.log('Error:', error);
      // 登录失败时的处理
      if (error.response) {
        // 服务器返回了错误响应
        const errorMessage = error.response.data.msg || '信息获取失败';
        message.error(errorMessage);
      } else if (error.request) {
        // 请求已发出，但没有收到响应
        message.error('请求失败，请检查网络连接');
      } else {
        // 发送请求时出了问题
        message.error('请求失败，请检查后端服务是否可用');
      }
    }
  };
  fetchData();
}, []);


return (
  <Space direction="horizontal" size={16}>
    <Card
      title="我的资产"
      style={{
        width: 570,
        height: 650,
      }}
    >
      <Statistic title="总资产(RMB)" value={totalAsset} />
          <Statistic title="浮动盈亏(RMB)" value={totalProfit} />
          <Statistic title="昨日盈亏(RMB)" value={yesterdayProfit} />
          <Statistic title="总盈亏率(%)" value={totalProfitRate} />
          <Statistic title="现金(RMB)" value={cash} />
          <Statistic title="股票价值(RMB)" value={stockValue} />
      
    </Card>

    <Space direction="vertical" size={16}>
    <Card
      
      title="在线充值"
      style={{
        width: 570,
        height: 320,
      }}
    >
      <p>请选择充值金额 ：</p>
      <br />
      <InputNumber addonBefore="+" addonAfter="¥" defaultValue={rechargeAmount} onChange={value => setRechargeAmount(value)}/>
      <br />
      <br />
      <br />
      <br />
      <Button type="primary" onClick={showModal1}>
        立即充值
      </Button>
      <Modal title="充值确认" open={isModalOpen1} onOk={handleOk1} onCancel={handleCancel1}>
        <p>是否确认充值{rechargeAmount}元？</p>
      </Modal>
    </Card>

    <Card      
      title="立即提现"
      style={{
        width: 570,
        height: 320,
      }}
    >
      <p>请选择提现金额 ：</p>
      <br />
      <InputNumber addonBefore="+" addonAfter="¥"  defaultValue={withdrawAmount}
          onChange={value => setWithdrawAmount(value)}
        />
      <br />
      <br />
      <br />
      <br />
      <Button type="primary" onClick={showModal2}>
        立即提现
      </Button>
      <Modal title="提现确认" open={isModalOpen2} onOk={handleOk2} onCancel={handleCancel2}>
        <p>是否确认提现{withdrawAmount}元？</p>
      </Modal>
    </Card>
    </Space>
  </Space>
)
};
export default Money;